package com.jron.cqiu.kernel.cmdline;

import java.io.*;

import com.jron.cqiu.util.StrUtil;

/**
 * Created by Intellij IDEA.
 *
 * @Author: Yejw
 * @Date: 2008-6-23
 * @Time: 15:23:38
 */
public class CommandObserver implements ICommandObserver {

    private BufferedReader br = null;
    private ICommandLineListener jronListener = null;
    private PrintWriter pw = null;

    public CommandObserver(InputStream is, ICommandLineListener cll) {
        this(new InputStreamReader(is), cll);
    }

    CommandObserver(Reader rdr, ICommandLineListener cll) {
        br = new BufferedReader(rdr);
        jronListener = cll;
        pw = new PrintWriter(System.out);
    }

    public void startReading() throws IOException {
        String cmd = null;
        int moreCommands = ICommandLineListener.CONTINUE_READING;
        pw.println(ICommandLineListener.WELCOME);
        while (moreCommands == ICommandLineListener.CONTINUE_READING) {
            pw.print(ICommandLineListener.PREFIX);
            pw.flush();
            cmd = br.readLine();
            moreCommands = jronListener.cmdEntered(pw, StrUtil.argsToStringArray(cmd));
            if (moreCommands == ICommandLineListener.STOP_READING) {
                pw.println(ICommandLineListener.GOODBYE);
                pw.flush();
                pw.close();
            }
            if (moreCommands == ICommandLineListener.GOON_BUT_STOP_READING) break;
        }
    }
}
